import javax.jms.*;
import javax.jms.Message;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class signalListen implements MessageListener {
    private List<Double> signalList=new ArrayList<Double>();
    int i=0;
    public void onMessage(Message message) {
        try {
            StreamMessage m=(StreamMessage)message;
            //没收到一条消息就放到list里面
            double mes=m.readDouble();
            signalList.add(mes);
            System.out.println("收到的随机信号: "+mes);

            //截取最近的N个随机信号进行求均值和方差
            int N=100;
            if (signalList.size()>=N){
                List<Double> tmp=signalList;
                int signalSize=tmp.size();
                List<Double> nums= tmp.subList(Math.max((signalSize - N ), 0), Math.max((signalSize), 0));

                //求平均值和方差
                double sum=0;
                for (double d:nums) {
                    sum+=d;
                }
                double mean=sum/nums.size();

                double variance=0;
                for (double d:nums) {
                    variance+=Math.pow(d-mean,2);
                }
                variance/=nums.size();
                //输出平均值和方差
                i=i+1;
                System.out.println("第"+i+"次发送随机信号分析结果");
                System.out.println(nums.size()+"个数的平均值:"+mean);
                System.out.println(nums.size()+"个数的方差:"+variance);
                //输出最大值和最小值
                double minNum=Collections.min(tmp);
                double maxNum=Collections.max(tmp);
                System.out.println("最大值:"+ maxNum+"\n"+"最小值:"+minNum+"\n");
                analyseConsumer analysePublisher=new analyseConsumer(1,"analyseResult");
                analysePublisher.sendMessage(minNum,maxNum,mean,variance);
                analysePublisher.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
